<template>
  <el-dialog
    title="选择标签"
    :visible.sync="visible"
    width="60%"
    append-to-body
  >
    <div class="wrapper">

      <div
        v-for="(el, ind) in list"
        :key="ind"
        class="mb-20"
      >
        <div class="item">
          {{ el.name }}
        </div>
        <div
          v-if="el.childrenList"
          class="flex flex-wrap"
        >
          <span
            v-for="(v, k) in el.childrenList"
            :key="k"
            :class="[toggleList.map(e => e.id).includes(v.id) ? 'selected' : '','sub-item']"
            @click="select(v)"
          >{{ v.name }}</span>
        </div>
      </div>
    </div>
    <div class="flex-end">
      <el-button @click="visible = false">取消</el-button>
      <el-button
        class="btn"
        type="primary"
        @click="confirm"
      >
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fetchAllLabeList } from '@/api/app/labelMng';
export default {
  name: 'selectLabel',
  props: {
    id: {
      type: [Object, String],
    },
    value: {
      type: Boolean,
      default: false,
    },
    selectList: { type: [Array] },
  },
  data() {
    return {
      list: [],
      toggleList: [],
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
  },
  watch: {
    async visible(val) {
      if (val) {
        await this.getList();
        this.toggleList = [...this.selectList];
      }
    },
  },
  methods: {
    async getList() {
      try {
        const res = await fetchAllLabeList();
        this.list = res.data.data;
      } catch (error) {
        throw new Error(error);
      }
    },
    confirm() {
      this.visible = false;
      this.$emit('selected', this.toggleList);
    },
    select(v) {
      const ind = this.toggleList.findIndex((el) => el.id === v.id);
      if (ind > -1) {
        this.toggleList.splice(ind, 1);
      } else {
        this.toggleList.push(v);
      }
    },
  },
};
</script>

<style lang='scss' scoped>
.mb-20 {
  margin-bottom: 20px;
}
.wrapper {
  max-height: 500px;
  overflow-y: scroll;
  margin-bottom: 20px;
  .item {
    font-size: 18px;
    font-weight: bold;
    color: #000;
  }
  .sub-item {
    margin-top: 20px;
    margin-right: 12px;
    border: 1px solid #000;
    padding: 3px 7px;
    cursor: pointer;
    box-sizing: border-box;
    color: #000;
    &.selected {
      background: $--color-primary;
      color: #fff;
      border: 1px solid $--color-primary;
    }
  }
}
</style>
